import 'package:flutter/material.dart';

class DragWidget extends StatefulWidget {
  @override
  _DragWidgetState createState() => _DragWidgetState();
}

class _DragWidgetState extends State<DragWidget> {
  double _marginLeft = 100;
  double _marginTop = 100;
  double _widgetHeight = 100;
  double _widgetWidth = 200;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
//    print("${MediaQuery.of(context).size.width}");
//    print("${MediaQuery.of(context).size.height}");
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Positioned(
            left: _marginLeft,
            top: _marginTop,
            child: GestureDetector(
              onHorizontalDragStart: _onHorizontalDragStart,
              onHorizontalDragUpdate: _onHorizontalDragUpdate,
              onHorizontalDragEnd: _onHorizontalDragEnd,
              child: Container(
                width: _widgetWidth,
                height: _widgetHeight,
                color: Colors.red,
              ),
            ),
          )
        ],
      ),
    );
  }

  double _lastDx = 0, _lastDy = 0;

  _onHorizontalDragUpdate(DragUpdateDetails details) {
    if ((details.globalPosition.dx - _lastDx).abs() > 0.5 || (details.globalPosition.dy - _lastDy).abs() > 0.5) {
      double dx = details.globalPosition.dx - _lastDx;
      double dy = details.globalPosition.dy - _lastDy;
      setState(() {
        _marginLeft += dx;
        _marginTop += dy;
      });
    }

    _lastDx = details.globalPosition.dx;
    _lastDy = details.globalPosition.dy;
  }

  _onHorizontalDragEnd(DragEndDetails details) {
    print("end _lasDx = $_lastDx, _lastDy = $_lastDy");
    if (_lastDx <= MediaQuery.of(context).size.width) {
      double finalX = 10;
      if ((MediaQuery.of(context).size.height - _lastDy) < (_widgetHeight)) {
        print("越过底部");
      }
    } else {}
  }

  void _onHorizontalDragStart(DragStartDetails details) {
    _lastDx = details.globalPosition.dx;
    _lastDy = details.globalPosition.dy;
  }
}
